package org.infosys.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.infosys.controller.handler.GolablExceptionHandler;
import org.infosys.entity.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RefreshScope//实时刷新远程配置
@RestController
public class UserController {

    @Value("${temp.notify}")
    private String notify;

    @GetMapping("/user/{id}")
    @SentinelResource(
            value = "GetById",
            blockHandler = "exceptionHandler",
            //blockHandlerClass = GolablExceptionHandler.class
            fallback = "getByIdfallback")
    public User getById(@PathVariable Long id) {
//        System.out.println("测试配置notify=" + notify);
        int i = 1 / 0; // 方法异常，触发熔断
        return new User().setId(1L).setName("zhangsan").setIntro("我是张三");
    }

    // 限流与阻塞处理 : 参数要和 被降级的方法参数一样
    public User exceptionHandler(@PathVariable Long id, BlockException ex) {
        ex.printStackTrace();
        System.out.println("限流了...");
        return new User().setId(-1L).setName("限流").setIntro("被限流了");
    }
    // 熔断降级
    public User getByIdfallback(@PathVariable Long id){
        System.out.println(notify);
        return new User(id,"zs:"+id, "熔断托底了");
    }
}
